﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Threading;

namespace Smart.Model
{
    public enum ServerType
    {
        ST_LOGIC = 0,
        ST_COUNT,
    }
    public class NetOutComponent : MonoBehaviour
    {
        class NetComponentImpl : NetworkComponent { }
        [SerializeField]
        NetworkProtocol Protocol = NetworkProtocol.TCP;
        NetComponentImpl impl = new NetComponentImpl();

        long[] sessions = new long[(int)ServerType.ST_COUNT];

        public void Send(ServerType serverType,int opcode,object message)
        {
            int idx = (int)serverType;
            if(idx >= 0 && idx < sessions.Length && null != impl)
            {
                var session = impl.Get(sessions[idx]);
                if(null != session)
                {
                    session.Send(opcode, message);
                }
            }
        }

        public bool Connect(ServerType eServer,string ipandport)
        {
            if (null == impl)
                return false;

            int idx = (int)eServer;
            if (idx < 0 || idx >= sessions.Length)
                return false;

            if(0L != sessions[idx])
            {
                impl.Remove(sessions[idx]);
                sessions[idx] = 0L;
            }

            var ss = impl.Create(ipandport);
            if (null != ss)
                sessions[idx] = ss.Id;

            return null != ss;
        }

        public void Close(ServerType eServer)
        {
            if (null == impl)
                return;

            int idx = (int)eServer;
            if (idx < 0 || idx >= sessions.Length)
                return;

            long id = sessions[idx];
            if (id == 0L)
                return;

            impl.Remove(id);
        }

        private void Awake()
        {
            Log.Info("[网络组件]:启动成功...");
            impl.Awake(this.Protocol);
            impl.MessagePacker = new ProtobufPacker();
            impl.MessageDispatcher = new NetMessageDispatcher();
            impl.MessageDecoder = new NetMessageDecoder();
        }

        private void Update()
        {
            impl.Update();
        }

        private void OnDestroy()
        {
            System.Array.Clear(sessions, 0, sessions.Length);
            impl.Dispose();
        }
    }
}